package com.weixing.mall.provider.controller.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.DatePattern;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.base.enums.IsEnableEnum;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.*;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.api.model.enums.TreeRoleEnum;
import com.weixing.mall.provider.api.model.vo.AgentTreeVo;
import com.weixing.mall.provider.api.model.vo.AgentVo;
import com.weixing.mall.provider.api.model.vo.KefuVo;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.model.domain.Agent;
import com.weixing.mall.provider.service.IAgentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName AgentCommonController
 * @Description
 * @Author Small
 * @Date 2020/4/12 13:56
 * @Version 1.0
 **/
@RestController
@RequestMapping("/agent/commn")
@Validated
@Api(value = "代理商", tags = "前端:代理商通用接口API")
public class AgentCommonController extends BaseController {

    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private IAgentService agentService;

    @ApiOperation(value = "校验代理商手机号是否允许注册")
    @GetMapping("checkMobile")
    public Result checkMobile(String mobile) {
        Agent byMobile = agentService.findByMobile(mobile);
        if (null != byMobile) {
            return ResultUtil.error("手机号已存在");
        }
        return ResultUtil.success();
    }


    @ApiOperation(value = "校验代理商优惠id是否有效")
    @GetMapping("checkSn")
    public Result checkSn(String agentSn) {
        Agent agent = agentService.findByAgentSn(agentSn);
        if (null == agent) {
            return ResultUtil.error("代理商优惠id不存在");
        } else {
            if (IsEnableEnum.DISABLE.getValue().equals(agent.getIsEnable()) ||
                    DateUtil.compare(new Date(), agent.getMaturityTime()) > 0
            ) {
                return ResultUtil.error("该优惠id对应的代理商不可用，或已过期");
            }
        }
        return ResultUtil.success();
    }


    @ApiOperation(value = "代理商通用结构树")
    @GetMapping("tree")
    public Result tree() {
        Result<List<KefuVo>> kefuVoResult = sysUserRpcService.loadKefu();
        if (!kefuVoResult.isSuccess()) {
            return ResultUtil.error();
        }
        List<KefuVo> voList = kefuVoResult.getData();
        // 最终返回的代理结构树
        List<AgentTreeVo> treeVos = Lists.newArrayList();
        List<Agent> agents = agentService.listAll();
        if (CollUtil.isNotEmpty(voList)) {
            voList.forEach(kefuVo -> {
                AgentTreeVo treeVo = new AgentTreeVo();
                treeVo.setId(kefuVo.getId());
                treeVo.setR(TreeRoleEnum.KEFU.getValue());
                treeVo.setRn(TreeRoleEnum.KEFU.getDesp());
                treeVo.setN(kefuVo.getRealName());
                treeVo.setL(0);

                List<AgentTreeVo> children = Lists.newArrayList();
                List<Agent> agents1 = agents.stream().filter((Agent a) -> a.getParentId().longValue() == 0 && a.getCustomerId().longValue() == kefuVo.getId().longValue()).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(agents1)) {
                    AgentTreeVo child = null;
                    for (Agent agent : agents1) {
                        child = new AgentTreeVo();
                        child.setId(agent.getId());
                        child.setR(TreeRoleEnum.AGENT.getValue());
                        child.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()).getDesp());
                        child.setL(agent.getAgentLevel());
                        child.setN(agent.getAgentName());
                        //  递归包装child
                        wrapper(child, agents);
                        children.add(child);
                    }
                    agents.removeAll(agents1);
                }
                treeVo.setC(children);
                treeVos.add(treeVo);
            });

        }
        return ResultUtil.success(treeVos);
    }

    private void wrapper(AgentTreeVo voNode, List<Agent> agents) {

        List<Agent> agents1 = agents.stream().filter((Agent a) -> a.getParentId().longValue() == voNode.getId().longValue()).collect(Collectors.toList());
        List<AgentTreeVo> children = Lists.newArrayList();
        AgentTreeVo child = null;
        if (CollUtil.isNotEmpty(agents1)) {
            for (Agent agent : agents1) {
                child = new AgentTreeVo();
                child.setId(agent.getId());
                child.setR(TreeRoleEnum.AGENT.getValue());
                child.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()).getDesp());
                child.setN(agent.getAgentName());
                child.setL(agent.getAgentLevel());
                wrapper(child);
                children.add(child);
            }
            agents.removeAll(agents1);
        }
        voNode.setC(children);
    }


    private void wrapper(AgentTreeVo voNode) {

        QueryWrapper<Agent> qwrapper = new QueryWrapper<>();
        qwrapper
                .eq("is_enable", IsEnableEnum.ENABLE.getValue())
                .eq("is_bind", WhetherEnum.YES.getValue())
                .eq("parent_id", voNode.getId())
                .orderByAsc("id");
        List<Agent> agents = agentService.list(qwrapper);
        List<AgentTreeVo> children = Lists.newArrayList();
        AgentTreeVo child = null;
        if (CollUtil.isNotEmpty(agents)) {
            for (Agent agent : agents) {
                child = new AgentTreeVo();
                child.setId(agent.getId());
                child.setR(TreeRoleEnum.AGENT.getValue());
                child.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()).getDesp());
                child.setN(agent.getAgentName());
                child.setL(agent.getAgentLevel());
                children.add(child);
                wrapper(child);
            }
        }
        voNode.setC(children);
    }


    @ApiOperation(value = "代理商通用结构树--客服")
    @GetMapping("tree/kefu")
    public Result treeForKefu(@SysInfo SysAuth sysAuth) {
        Result<KefuVo> kefuVoResult = sysUserRpcService.loadKefuById(sysAuth.getUid());
        if (!kefuVoResult.isSuccess()) {
            return ResultUtil.error();
        }
        KefuVo kefuVo = kefuVoResult.getData();
        // 最终返回的代理结构树
        List<AgentTreeVo> treeVos = Lists.newArrayList();
        AgentTreeVo treeVo = new AgentTreeVo();
        treeVo.setId(kefuVo.getId());
        treeVo.setR(TreeRoleEnum.KEFU.getValue());
        treeVo.setRn(TreeRoleEnum.KEFU.getDesp());
        treeVo.setN(kefuVo.getRealName());
        treeVo.setL(0);
        QueryWrapper<Agent> wrapper = new QueryWrapper<>();
        wrapper
                .eq("is_enable", IsEnableEnum.ENABLE.getValue())
                .eq("is_bind", WhetherEnum.YES.getValue())
                .eq("parent_id", 0)
                .eq("customer_id", kefuVo.getId())
                .orderByAsc("id");
        // 经销商
        List<Agent> rootList = agentService.list(wrapper);
        List<AgentTreeVo> children = Lists.newArrayList();
        if (CollUtil.isNotEmpty(rootList)) {
            AgentTreeVo child = null;
            for (Agent agent : rootList) {
                child = new AgentTreeVo();
                child.setId(agent.getId());
                child.setR(TreeRoleEnum.AGENT.getValue());
                child.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()).getDesp());
                child.setN(agent.getAgentName());
                child.setL(agent.getAgentLevel());
                children.add(child);
                //  递归包装child
                wrapper(child);
            }
        }
        treeVo.setC(children);
        treeVos.add(treeVo);
        return ResultUtil.success(treeVos);
    }

    @ApiOperation(value = "代理商通用结构树--代理")
    @GetMapping("tree/agent")
    public Result treeForAgent(@AgentInfo AgentAuth auth) {
        long agentId = auth.getAid();
        Agent rootAgent = agentService.getById(agentId);
        // 最终返回的代理结构树
        List<AgentTreeVo> treeVos = Lists.newArrayList();
        AgentTreeVo treeVo = new AgentTreeVo();
        treeVo.setId(rootAgent.getId());
        treeVo.setR(TreeRoleEnum.AGENT.getValue());
        treeVo.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, rootAgent.getAgentLevel()).getDesp());
        treeVo.setN(rootAgent.getAgentName());
        treeVo.setL(rootAgent.getAgentLevel());
        wrapper(treeVo);
        treeVos.add(treeVo);
        return ResultUtil.success(treeVos);
    }

    @ApiOperation(value = "代理商通用结构树--代理")
    @GetMapping("tree/app/agent")
    public Result treeForAppAgent(@RequestParam(value = "tradeFlag", defaultValue = "0") String tradeFlag) {
        long agentId = AuthUtil.getMemberExt().getAbid();
        Agent rootAgent = agentService.getById(agentId);
        // 最终返回的代理结构树
        List<AgentTreeVo> treeVos = Lists.newArrayList();
        AgentTreeVo treeVo = new AgentTreeVo();
        treeVo.setId(rootAgent.getId());
        treeVo.setR(TreeRoleEnum.AGENT.getValue());
        treeVo.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, rootAgent.getAgentLevel()).getDesp());
        treeVo.setN(rootAgent.getAgentName());
        treeVo.setL(rootAgent.getAgentLevel());
        if ("1".equals(tradeFlag)) {
            wrapperWithTradeFlag(treeVo);
        } else {
            wrapper(treeVo);
        }
        treeVos.add(treeVo);
        return ResultUtil.success(treeVos);
    }


    private void wrapperWithTradeFlag(AgentTreeVo voNode) {
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        List<Agent> agents = agentService.list(getAgentcQuery(voNode));
        if (CollUtil.isNotEmpty(agents)) {
            wrapperFilter(today, voNode, agents);
        }
    }

    private void wrapperFilter(String today, AgentTreeVo voNode, List<Agent> agents) {
        //        CNM! 什么尼玛的破需求,看不动了
        //        我要崩溃了！！！
        //        效果出来了，我好方
        List<AgentTreeVo> children = Lists.newArrayList();
        AgentTreeVo child = null;
        int cLevel = voNode.getL().intValue() + 1;
        while (cLevel < 5) {
            int finalCLevel = cLevel;
            List<Agent> childs = Lists.newArrayList();

            switch (voNode.getL()) {
                case 1:
                    childs = agents.stream().filter((Agent m1) -> m1.getAgentLevel().intValue() == finalCLevel && m1.getDealerId().longValue() == voNode.getId().longValue()).collect(Collectors.toList());
                    break;
                case 2:
                    childs = agents.stream().filter((Agent m1) -> m1.getAgentLevel().intValue() == finalCLevel && m1.getLevel1st().longValue() == voNode.getId().longValue()).collect(Collectors.toList());
                    break;
                case 3:
                    childs = agents.stream().filter((Agent m1) -> m1.getAgentLevel().intValue() == finalCLevel && m1.getLevel2nd().longValue() == voNode.getId().longValue()).collect(Collectors.toList());
                    break;
                case 4:
                    childs = agents.stream().filter((Agent m1) -> m1.getAgentLevel().intValue() == finalCLevel && m1.getLevel3rd().longValue() == voNode.getId().longValue()).collect(Collectors.toList());
                    break;
                default:
                    break;
            }


            if (CollUtil.isNotEmpty(childs)) {
                List<Agent> dropList = Lists.newArrayList();
                for (Agent agent : childs) {
                    String tradeDate = StringUtil.isBlank(agent.getTradeDate()) ? "" : agent.getTradeDate();
                    if (today.equals(tradeDate)) {
                        child = new AgentTreeVo();
                        child.setId(agent.getId());
                        child.setR(TreeRoleEnum.AGENT.getValue());
                        child.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()).getDesp());
                        child.setN(agent.getAgentName());
                        child.setL(agent.getAgentLevel());
                        children.add(child);
                        wrapperFilter(today, child, agents);
                    }
                    dropList.add(agent);
                }
                agents.removeAll(dropList);
            }
            cLevel += 1;
        }
        voNode.setC(children);
    }


    private QueryWrapper<Agent> getAgentcQuery(AgentTreeVo voNode) {
        QueryWrapper<Agent> qwrapper = new QueryWrapper<>();
        qwrapper
                .eq("is_enable", IsEnableEnum.ENABLE.getValue())
                .eq("is_bind", WhetherEnum.YES.getValue());
        Integer level = voNode.getL();
        switch (level) {
            case 1:
                qwrapper.eq("dealer_id", voNode.getId());
                break;
            case 2:
                qwrapper.eq("level1st", voNode.getId());
                break;
            case 3:
                qwrapper.eq("level2nd", voNode.getId());
                break;
            default:
                break;
        }
        qwrapper.orderByAsc("agent_level", "id");
        return qwrapper;
    }

    @ApiOperation(value = "代理商结构树--领导看板")
    @GetMapping("tree/leader")
    @NoNeedAccess
    public Result treeForLeaderShow(String agentName) {
        //加载所有客服 新增客服层级 2020年11月6日
        Result<List<KefuVo>> kefuVoResult = sysUserRpcService.loadKefu();
        if (!kefuVoResult.isSuccess() || kefuVoResult.getData() == null) {
            return ResultUtil.error();
        }
        List<KefuVo> kefuList = kefuVoResult.getData();
        //客服层级树装载
        List<Map<String, Object>> topList = Lists.newArrayList();
        for (KefuVo kf:kefuList){
            Map<String, Object> kefuMap = new HashMap<>();
            kefuMap.put("id", kf.getId());
            kefuMap.put("name", kf.getRealName());
            kefuMap.put("mobile", kf.getMobile());
            loadAgent(kf.getId(),agentName,kefuMap);
            topList.add(kefuMap);
        }

        return ResultUtil.success(topList);
    }

    private Map<String, Object> loadAgent(Long kefuId,String agentName,Map<String, Object> kefuMap){
        //查询所有代理商
        QueryWrapper<Agent> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(agentName)) {
            qw.like("agent_name", agentName);
        }
        if(kefuId != null){
            qw.eq("customer_id",kefuId);
        }
        qw.eq("is_enable", IsEnableEnum.ENABLE.getValue())
                .eq("is_bind", WhetherEnum.YES.getValue())
                .orderByAsc("id");
        //封装代理商结构树
        List<Agent> allAgentList = agentService.list(qw);
        //树装载
        List<Map<String, Object>> parentList = Lists.newArrayList();
        for (Agent a : allAgentList) {
            if ((StrUtil.isNotEmpty(agentName) || kefuId != null) && a.getParentId() == 0) {//以名称搜索结果为顶级
                Map<String, Object> parentMap = new HashMap<>();
                loadInfo(a, parentMap);
                loadChild(a.getId(), parentMap, allAgentList);
                parentMap.put("teamNum",teamNum(a,allAgentList));
                parentList.add(parentMap);
            }else {//默认以经销商一级为顶级
                if (AgentLevelEnum.DEALER.getValue().equals(a.getAgentLevel())) {
                    //初始数量
                    Integer teamNum = 0;
                    Map<String, Object> parentMap = new HashMap<>();
                    loadInfo(a, parentMap);
                    loadChild(a.getId(), parentMap, allAgentList);
                    parentMap.put("teamNum",teamNum(a,allAgentList));
                    parentList.add(parentMap);
                }
            }
        }
        //下级代理商
        kefuMap.put("child",parentList);
        //代理商总数量
        kefuMap.put("teamNum",allAgentList.size());
        return kefuMap;
    }

    private void loadChild(Long parentId, Map<String, Object> parentMap, List<Agent> allAgentList) {
        List<Map<String, Object>> childList = Lists.newArrayList();
        for (Agent a : allAgentList) {
            if (parentId.equals(a.getParentId())) {
                Map<String, Object> childMap = new HashMap<>();
                loadInfo(a, childMap);
                loadChild(a.getId(), childMap, allAgentList);
                childMap.put("teamNum",teamNum(a,allAgentList));
                childList.add(childMap);
            }
        }
        parentMap.put("child", childList);
    }

    private Integer teamNum(Agent agent,List<Agent> allAgentList){
        List<Agent> childs = Lists.newArrayList();
        switch (agent.getAgentLevel()) {
            case 1:
                childs = allAgentList.stream().filter((Agent m1) -> !m1.getId().equals(agent.getId()) && m1.getDealerId().longValue() == agent.getId().longValue()).collect(Collectors.toList());
                break;
            case 2:
                childs = allAgentList.stream().filter((Agent m1) -> !m1.getId().equals(agent.getId()) && m1.getLevel1st().longValue() == agent.getId().longValue()).collect(Collectors.toList());
                break;
            case 3:
                childs = allAgentList.stream().filter((Agent m1) -> !m1.getId().equals(agent.getId()) && m1.getLevel2nd().longValue() == agent.getId().longValue()).collect(Collectors.toList());
                break;
            case 4:
                childs = allAgentList.stream().filter((Agent m1) -> !m1.getId().equals(agent.getId()) && m1.getLevel3rd().longValue() == agent.getId().longValue()).collect(Collectors.toList());
                break;
            default:
                break;
        }
        return childs.size();
    }

    private void loadInfo(Agent a, Map<String, Object> Map) {
        Map.put("id", a.getId());
        Map.put("name", a.getAgentName());
        Map.put("mobile", a.getMobile());
        Map.put("wechat", a.getWechatNum());

        Map.put("parentId", a.getParentId());
        Map.put("level", a.getAgentLevel());
    }


    @ApiOperation(value = "代理商通用结构树--推荐人列表（客服专员，管理员）")
    @GetMapping("tree/bonus")
    public Result treeForBonus() {

        Result<List<KefuVo>> kefuVoResult = sysUserRpcService.loadKefu();
        if (!kefuVoResult.isSuccess()) {
            return ResultUtil.error();
        }
        List<KefuVo> voList = kefuVoResult.getData();
        // 最终返回的代理结构树
        List<AgentTreeVo> treeVos = Lists.newArrayList();
        if (CollUtil.isNotEmpty(voList)) {
            voList.forEach(kefuVo -> {
                AgentTreeVo treeVo = new AgentTreeVo();
                treeVo.setId(kefuVo.getId());
                treeVo.setR(TreeRoleEnum.KEFU.getValue());
                treeVo.setRn(TreeRoleEnum.KEFU.getDesp());
                treeVo.setN(kefuVo.getRealName());
                treeVo.setL(0);
                // 经销商
                List<Agent> rootList = agentService.selectObligee(kefuVo.getId());
                List<AgentTreeVo> children = Lists.newArrayList();
                if (CollUtil.isNotEmpty(rootList)) {
                    AgentTreeVo child = null;
                    for (Agent agent : rootList) {
                        child = new AgentTreeVo();
                        child.setId(agent.getId());
                        child.setR(TreeRoleEnum.AGENT.getValue());
                        child.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()).getDesp());
                        child.setL(agent.getAgentLevel());
                        child.setN(agent.getAgentName());
                        // 查询是否有下级
                        wrapperBonus(child);
                        children.add(child);
                    }
                }
                treeVo.setC(children);
                treeVos.add(treeVo);
            });

        }
        return ResultUtil.success(treeVos);
    }

    private void wrapperBonus(AgentTreeVo voNode) {

        List<Agent> childList = agentService.selectObligeeChild(voNode.getId());
        if (CollUtil.isNotEmpty(childList)) {
            AgentTreeVo child = null;
            List<AgentTreeVo> children = Lists.newArrayList();
            for (Agent agent : childList) {
                child = new AgentTreeVo();
                child.setId(agent.getId());
                child.setR(TreeRoleEnum.AGENT.getValue());
                child.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()).getDesp());
                child.setL(agent.getAgentLevel());
                child.setN(agent.getAgentName());
                children.add(child);
            }
            voNode.setC(children);
        }
    }


    @ApiOperation(value = "代理商通用结构树--推荐人列表(客服专用)")
    @GetMapping("tree/bonus/kefu")
    public Result treeForBonusForKefu() {
        SysAuth sysAuth = AuthUtil.getSysExt();
        Result<KefuVo> kefuVoResult = sysUserRpcService.loadKefuById(sysAuth.getUid());
        if (!kefuVoResult.isSuccess()) {
            return ResultUtil.error();
        }
        KefuVo kefuVo = kefuVoResult.getData();
        // 最终返回的代理结构树
        List<AgentTreeVo> treeVos = Lists.newArrayList();

        AgentTreeVo treeVo = new AgentTreeVo();
        treeVo.setId(kefuVo.getId());
        treeVo.setR(TreeRoleEnum.KEFU.getValue());
        treeVo.setRn(TreeRoleEnum.KEFU.getDesp());
        treeVo.setN(kefuVo.getRealName());
        treeVo.setL(0);
        // 经销商
        List<Agent> rootList = agentService.selectObligee(kefuVo.getId());
        List<AgentTreeVo> children = Lists.newArrayList();
        if (CollUtil.isNotEmpty(rootList)) {
            AgentTreeVo child = null;
            for (Agent agent : rootList) {
                child = new AgentTreeVo();
                child.setId(agent.getId());
                child.setR(TreeRoleEnum.AGENT.getValue());
                child.setRn(EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel()).getDesp());
                child.setL(agent.getAgentLevel());
                child.setN(agent.getAgentName());
                wrapperBonus(child);
                children.add(child);
            }
        }
        treeVo.setC(children);
        treeVos.add(treeVo);


        return ResultUtil.success(treeVos);
    }


    @ApiOperation(value = "查询有分红关系的代理")
    @GetMapping("bonusAgent/{agentId}")
    public Result bonusAgent(@PathVariable Long agentId) {
        List<AgentVo> agents = agentService.selectBonusAgent(agentId);
        return ResultUtil.success(agents);
    }
}
